package com.tlgen.modules.hospitalized.service.impl;

import com.tlgen.common.exception.EntityExistException;
import com.tlgen.common.utils.FileUtil;
import com.tlgen.common.utils.PageUtil;
import com.tlgen.common.utils.QueryHelp;
import com.tlgen.common.utils.ValidationUtil;
import com.tlgen.modules.hospitalized.domain.Record;
import com.tlgen.modules.hospitalized.repository.RecordRepository;
import com.tlgen.modules.hospitalized.service.RecordService;
import com.tlgen.modules.hospitalized.service.dto.RecordDto;
import com.tlgen.modules.hospitalized.service.dto.RecordQueryCriteria;
import com.tlgen.modules.hospitalized.service.mapper.RecordMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "Record")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RecordServiceImpl implements RecordService {

    private final RecordRepository recordRepository;

    private final RecordMapper recordMapper;

    public RecordServiceImpl(RecordRepository recordRepository, RecordMapper recordMapper) {
        this.recordRepository = recordRepository;
        this.recordMapper = recordMapper;
    }

    /**
     * 根据登记人员名称获取信息
     * @param name
     * @return
     */
    @Override
    @Cacheable(key = "'loadUserByName:'+#p0")
    public RecordDto findByName(String name) {
        Record record1;
        record1 = recordRepository.findByName(name);
        if(record1==null){
            throw new EntityExistException(Record.class,"record",name);
        }else {
            return recordMapper.toDto(record1);
        }
    }

    /**
     * 不带条件分页查询
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return recordMapper.toDto(recordRepository.findAll(pageable).getContent());
    }


    /**
     * 带条件分页查询
     * @param criteria 条件
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(RecordQueryCriteria criteria, Pageable pageable) {
        Page<Record> page = recordRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(recordMapper::toDto));
    }

    /**
     * 带条件不分页查询
     * @param criteria 条件
     * @return
     */
    @Override
    @Cacheable
    public List<RecordDto> queryAll(RecordQueryCriteria criteria) {
        return recordMapper.toDto(recordRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 新增
     * @param resources /
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public RecordDto create(Record resources) {
        if (recordRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Record.class, "record", resources.getName());
        }
        return recordMapper.toDto(recordRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(Record resources) {
        Record record = recordRepository.findById(resources.getId()).orElseGet(Record::new);
        ValidationUtil.isNull(record.getId(),"Record","id",resources.getId());

        record.setName(resources.getName());
        record.setSex(resources.getSex());
        record.setAddress(resources.getAddress());
        record.setAge(resources.getAge());
        record.setNation(resources.getNation());
        record.setWedding(resources.getWedding());
        record.setMedicinalcode(resources.getMedicinalcode());
        record.setAddress(resources.getAddress());
        record.setPhone(resources.getPhone());
        record.setHistory(resources.getHistory());
        recordRepository.save(record);
    }

    /**
     * 删除
     * @param ids /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            recordRepository.deleteById(id);
        }
    }

    /**
     * 导出数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<RecordDto> RecordDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RecordDto recordDto : RecordDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", recordDto.getName());
            map.put("性别", recordDto.getSex());
            map.put("年龄", recordDto.getAge());
            map.put("民族", recordDto.getNation().getName());
            map.put("婚否", recordDto.getWedding());
            map.put("医保号", recordDto.getMedicinalcode());
            map.put("地址", recordDto.getAddress());
            map.put("手机号码", recordDto.getPhone());
            map.put("药物过敏", recordDto.getHistory());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 根据Id查询
     * @param id /
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public RecordDto findById(long id) {
        Record Record = recordRepository.findById(id).orElseGet(Record::new);
        ValidationUtil.isNull(Record.getId(),"Record","id",id);
        return recordMapper.toDto(Record);
    }

}
